import { ref, inject, watch, customRef } from 'vue';
import { FormContextKey } from '../Form/index.js';
import { FormItemContextKey } from '../FormItem/index.js';

function formFieldRef(props, emit, defaultValue) {
  const value = ref(props.modelValue ?? defaultValue);
  const ctx = inject(FormContextKey, null);
  const formItemCtx = inject(FormItemContextKey, null);
  const name = props.name || formItemCtx?.name;
  watch(() => props.modelValue, (val) => {
    value.value = val;
  });
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value.value;
      },
      set(newValue) {
        value.value = newValue;
        emit("update:modelValue", newValue);
        if (props.asFormField !== false) {
          ctx?.onChange(name, newValue);
        }
        trigger();
      }
    };
  });
}

export { formFieldRef as default };
